package com.ewing.common.filter.stat;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.ewing.busi.stat.dao.StatAccessLogDao;
import com.ewing.busi.stat.model.StatAccessLog;
import com.ewing.common.utils.BasePraramUtils;
import com.ewing.core.auth.HttpSessionUtils;
import com.ewing.utils.CodecUtils;
import com.ewing.utils.IntegerUtils;
import com.ewing.utils.JsonUtils;

/**
 * 统计打点
 * 
 * created by Tianxin on 2016年4月24日 下午4:38:05
 */
@Repository("statFilter")
public class StatFilter implements Filter{
  

  /**
   * 默认生成的该类的LOG记录器，使用slf4j组件。避免产生编译警告，使用protected修饰符。
   */
  private final static Logger LOG = LoggerFactory.getLogger(StatFilter.class);
  
  @Resource
  private StatAccessLogDao statAccessLogDao;

  @Override
  public void destroy() {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    
    StatAccessLog log = new StatAccessLog();
    log.setReferer(req.getHeader("referer"));
    log.setAccessUrl(req.getRequestURI());
    log.setSessionId(BasePraramUtils.getSessionId());
    log.setCustomerId(HttpSessionUtils.getCusId());
    String shopIdStr = CodecUtils.decodeBase64(BasePraramUtils.getShopId());
    log.setShopId(IntegerUtils.parseInt(shopIdStr));
    log.setUserId(0);
    log.setThirdPlatform(HttpSessionUtils.getThirdPlatformId());
    log.setThirdUserId(HttpSessionUtils.getMarkId());
    log.setIp(req.getRemoteAddr());
    log.setBrowser(req.getHeader("User-Agent"));
    
    LOG.info(JsonUtils.toJson(log));
    chain.doFilter(req, resp);
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}
